%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%                 Sockets                   %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

user:runtime_entry(start) :- server.

:-use_module(library(sockets)).
:-use_module(library(random)).
:-use_module(library(spld)).

:- include('network_cannon.pl').


% launch me in sockets mode
server:-
	random(2048, 60000, Port),
	write('Server starting at: '), write(Port), nl,
	socket_server_open(Port, Socket),
	socket_server_accept(Socket, Client, Stream, [type(text)]),
	write('Accepted connection from: '), write(Client), nl,
	serverLoop(Stream),
	socket_server_close(Socket).

% wait for commands
serverLoop(Stream) :-
	repeat,	
	read(Stream, ClientMsg),
	write('Received: '), write(ClientMsg), nl,
	parse_input(ClientMsg, MyReply),
	format(Stream, '~q.~n', [MyReply]),
	write('Wrote: '), write(MyReply), nl,
	flush_output(Stream),
	(ClientMsg == quit; ClientMsg == end_of_file), !.

parse_input(execute(Board, Movement, Player), Answer) :-
	execute(Player, Movement, Board, Answer), !.
	
parse_input(check_end(Arg1, _), Answer) :-
	check_end(Arg1, Answer), !.
	
parse_input(initialize, Board) :-
	write('New game starting...'), nl, 
	initial_game(Board), !.
	
parse_input(quit, ok-bye) :- !.

parse_input(_, error):-
	write('Unrecognized command'), nl, 
	!.
	